package io.github.jyrmc.gmcp.generate

import io.github.jyrmc.gmcp.utils.PrintInfoUtil
import freemarker.template.Configuration
import freemarker.template.Template
import io.github.jyrmc.gmcp.common.FreemarkerConstant
import java.io.*
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.*

/**
 *
 * @描述：生成markdown文档
 * @时间：2021/3/1 5:21 下午
 * @作者：jy
 * @公司：贵州中测信息技术有限公司
 */

object GenerateMarkdown {


    /**
     * 生成文档
     */
    fun freemarkerGenerate(
        config: Configuration,
        projectPath: String,
        dataMap: MutableMap<String, Any?>,
        databaseName: String
    ) {
        val fileName = "doc-${databaseName}-${SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(Date())}.md"
        val fileFullPath = "${projectPath}/${fileName}"

        val file = File(fileFullPath)
        if (file.exists()) {
            println("message: file [${fileName}] is exists.")
            return
        }
        if (!file.exists()) {
            file.parentFile.mkdirs()
            PrintInfoUtil.printCreateFold(file.parentFile.absolutePath)
        }

        val template: Template = config.getTemplate(
             // "${FreemarkerConstant.BASIC_DIC}/GenerateMarkdown.ftl",
            "/GenerateMarkdownSample.ftl",
            "UTF-8"
        )

        val out: Writer = BufferedWriter(OutputStreamWriter(FileOutputStream(fileFullPath), StandardCharsets.UTF_8))
        template.process(dataMap, out)
        out.flush()
        out.close()

        PrintInfoUtil.printCreateFile(fileFullPath)
    }
}
